<?php
namespace app\api\controller;

use app\common\controller\ApiBaseController;
use app\common\model\WsmessageModel;
use think\Validate;

class WsmessageController extends ApiBaseController
{
    private $msg = '';

    public function index()
    {
        self::testPost();

        $data = self::check_data();
        if(!$data){
            $this->error($this->msg);
        }

        $model = WsmessageModel::create($data);
        if (!$model) {
            $this->error('提示：新增失败!');
        }
        return $this->success('恭喜：留言成功，等待管理员审核！');
    }

    private function check_data()
    {
        $init_data = [
            'siteid' => '0', 
            'columnid' => '0', 
            'name' => '', 
            'phone' => '', 
            'email' => '', 
            'title' => '', 
            'desc' => '', 
        ];
        $param = $this->request->param();

        if(isset($param['captcha'])){
            if(!captcha_check($param['captcha'])){
                $this->msg = '验证码错误！';
                return false;
            };
        }
        

        $param = array_merge($init_data, $param);
        //dump($param);
        $rule = [
            'wsmessage_siteid' => 'require|number|gt:0',
            'wsmessage_columnid' => 'require|number|gt:0',
            'wsmessage_name' => 'require',
            'wsmessage_phone' => 'require',
            'wsmessage_email' => 'email',
        ];
        $msg = [
            'wsmessage_siteid.require' => '提示：siteid 必填！',
            'wsmessage_siteid.number' => '提示：siteid 必须为数字！',
            'wsmessage_siteid.gt' => '提示：siteid 必须大于 0！',
            'wsmessage_columnid.require' => '提示：columnid 必填！',
            'wsmessage_columnid.number' => '提示：columnid 必须为数字！',
            'wsmessage_columnid.gt' => '提示：columnid 必须大于 0！',
            'wsmessage_name.require' => '提示：姓名必须填写！',
            'wsmessage_phone.require' => '提示：电话必须填写！',
            'wsmessage_email.email' => '提示：邮箱格式不正确！',
        ];

        $data = [
            'wsmessage_siteid' => $param['siteid'],
            'wsmessage_columnid' => $param['columnid'],
            'wsmessage_name' => $param['name'],
            'wsmessage_phone' => $param['phone'],
            'wsmessage_email' => $param['email'],
            'wsmessage_title' => $param['title'],
            'wsmessage_desc' => $param['desc'],
            'wsmessage_ip' => '',
        ];

        $validate = Validate::make($rule, $msg);
        $result = $validate->check($data);
        if (!$result) {
            $this->msg = $validate->getError();
            return false;
        }
        return $data;
    }
}
